<template>
  <MainLayout>
    <div class="my-day-page">
      <!-- 页面标题 -->
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold flex items-center">
          <n-icon size="24" class="mr-2">
            <CalendarOutline />
          </n-icon>
          我的一天
        </h2>
        <n-button 
          type="primary" 
          @click="showCreateTaskDialog = true"
        >
          <template #icon>
            <n-icon size="18">
              <AddOutline />
            </n-icon>
          </template>
          添加任务
        </n-button>
      </div>
      
      <!-- 日期显示 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-4 mb-6">
        <h3 class="text-lg font-semibold">{{ formatDate(new Date()) }}</h3>
        <p class="text-gray-500 dark:text-gray-400 mt-1">
          今天是 {{ getDayOfWeek(new Date()) }}，这里展示您标记为"我的一天"的任务
        </p>
      </div>
      
      <!-- 任务列表 -->
      <div v-if="isLoading" class="flex justify-center items-center py-12">
        <n-spin size="large" />
      </div>
      
      <div v-else-if="myDayTasks.length === 0" class="text-center py-12">
        <n-empty description="今天还没有标记为'我的一天'的任务">
          <template #icon>
            <n-icon size="48">
              <CalendarOutline />
            </n-icon>
          </template>
          <n-button type="primary" @click="showCreateTaskDialog = true">
            添加任务到我的一天
          </n-button>
        </n-empty>
      </div>
      
      <div v-else>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <TaskCard 
            v-for="task in myDayTasks" 
            :key="task.task_id"
            :task="task"
          />
        </div>
      </div>
      
      <!-- 创建任务对话框 -->
      <n-dialog v-model:show="showCreateTaskDialog" title="创建任务" width="600px">
        <n-form 
          :model="createTaskForm" 
          :rules="createTaskRules"
          ref="createTaskFormRef"
        >
          <n-form-item path="title">
            <n-input 
              v-model:value="createTaskForm.title" 
              placeholder="请输入任务标题"
              autofocus
            />
          </n-form-item>
          
          <n-form-item path="group_id">
            <n-select 
              v-model:value="createTaskForm.group_id" 
              placeholder="请选择任务分组"
              :options="groupOptions"
            >
              <template #prefix>
                <n-icon size="18">
                  <ListOutline />
                </n-icon>
              </template>
            </n-select>
          </n-form-item>
          
          <n-form-item path="description">
            <n-input
              v-model:value="createTaskForm.description"
              type="textarea"
              placeholder="请输入任务描述"
              :autosize="{ minRows: 3, maxRows: 6 }"
            />
          </n-form-item>
          
          <div class="grid grid-cols-2 gap-4">
            <n-form-item>
              <n-date-picker 
                v-model:value="createTaskForm.due_date" 
                type="date"
                placeholder="选择截止日期"
              />
            </n-form-item>
            
            <div class="flex items-center space-x-4">
              <n-checkbox v-model:checked="createTaskForm.is_important">重要任务</n-checkbox>
              <n-checkbox v-model:checked="createTaskForm.is_my_day" :disabled="true" checked>
                我的一天
              </n-checkbox>
            </div>
          </div>
        </n-form>
        <template #footer>
          <div class="flex justify-end space-x-2">
            <n-button @click="showCreateTaskDialog = false">取消</n-button>
            <n-button 
              type="primary" 
              @click="handleCreateTask"
              :loading="isCreating"
            >
              创建任务
            </n-button>
          </div>
        </template>
      </n-dialog>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import MainLayout from '@/layouts/MainLayout.vue'
import TaskCard from '@/components/TaskCard.vue'
import { useGroupStore } from '@/store/group'
import { CreateTaskRequest } from '@/types'
import { 
  CalendarOutline, 
  AddOutline, 
  ListOutline
} from '@vicons/ionicons5'
import type { FormInstance } from 'naive-ui'
import { useRequest, useFetcher } from 'alova'
import { getMyDayTasks, createTask as createTaskApi } from '@/api/task'

// 状态
const showCreateTaskDialog = ref<boolean>(false)
const createTaskFormRef = ref<FormInstance | null>(null)

// 获取分组store
const groupStore = useGroupStore()

// 从store获取数据
const groups = computed(() => groupStore.groups)
const isLoadingGroups = computed(() => groupStore.isLoading)
const currentGroupId = computed(() => groupStore.currentGroupId)

// 使用useRequest获取"我的一天"任务列表
const {
  data: myDayTasksData,
  loading: isLoadingTasks,
  error,
  refresh: fetchMyDayTasks
} = useRequest(
  () => getMyDayTasks(),
  {
    immediate: false
  }
)

// 计算"我的一天"任务列表
const myDayTasks = computed(() => myDayTasksData.value?.list || [])

// 总加载状态
const isLoading = computed(() => isLoadingTasks.value || isLoadingGroups.value)

// 分组选项（用于创建任务时选择分组）
const groupOptions = computed(() => {
  return groups.value.map(group => ({
    label: group.name,
    value: group.group_id
  }))
})

// 创建任务表单
const createTaskForm = reactive<CreateTaskRequest>({
  group_id: currentGroupId.value,
  title: '',
  description: '',
  is_important: false,
  is_my_day: true, // 默认标记为我的一天
  due_date: undefined
})

// 创建任务表单规则
const createTaskRules = {
  title: [
    { required: true, message: '请输入任务标题', trigger: 'blur' },
    { min: 1, max: 100, message: '任务标题长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  group_id: [
    { required: true, message: '请选择任务分组', trigger: 'blur' }
  ]
}

// 使用useFetcher创建任务
const {
  loading: isCreating,
  send: createTask
} = useFetcher(createTaskApi)

// 格式化日期
const formatDate = (date: Date) => {
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  }).format(date)
}

// 获取星期几
const getDayOfWeek = (date: Date) => {
  const days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  return days[date.getDay()]
}

// 处理创建任务
const handleCreateTask = async () => {
  if (!createTaskFormRef.value) return
  
  try {
    await createTaskFormRef.value.validate()
    await createTask(createTaskForm)
    showCreateTaskDialog.value = false
    // 重置表单
    resetCreateTaskForm()
    // 刷新"我的一天"任务列表
    fetchMyDayTasks()
  } catch (error) {
    console.error('创建任务失败:', error)
  }
}

// 重置创建任务表单
const resetCreateTaskForm = () => {
  createTaskForm.title = ''
  createTaskForm.description = ''
  createTaskForm.is_important = false
  createTaskForm.is_my_day = true
  createTaskForm.due_date = undefined
  createTaskForm.group_id = currentGroupId.value
  createTaskFormRef.value?.restoreValidation()
}

// 页面加载时获取数据
onMounted(async () => {
  // 获取分组列表
  await groupStore.fetchGroups()
  // 获取"我的一天"任务
  fetchMyDayTasks()
})
</script>

<style scoped>
.my-day-page {
  max-width: 1200px;
  margin: 0 auto;
}
</style>
